package com.okq.action;

import com.okq.action.base.BaseActionSupport;
import com.okq.entity.Notice;
import com.okq.entity.User;
import com.okq.service.ILogService;
import com.okq.service.INoticeService;
import com.okq.util.BaseTool;
import com.okq.util.PublicClass;
import com.okq.util.TimeTool;
import com.okq.util.page.Page;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.PrintWriter;
import java.util.*;

/**
 * 描述 : 公告通知Action
 * 作者 : zdl
 * 日期 : 2017/7/5 10:47
 */
public class NoticeAction extends BaseActionSupport {
    private static final long serialVersionUID = -961649689226386024L;
    /**
     * 公告通知接口
     */
    @Autowired
    private INoticeService noticeServiceImpl;
    /**
     * 系统日志接口
     */
    @Autowired
    private ILogService logServiceImpl;

    /**
     * 日志
     */
    private static final Logger logger = Logger.getLogger(NoticeAction.class);
    /**
     * 分页开始条数
     */
    private int iDisplayStart;

    /**
     * 每页显示条数
     */
    private int iDisplayLength;

    private String id;
    private Notice notice;
    private String type;

    /**
     * 查询最新置顶的公告通知
     *
     * @return json
     */
    public String getLastTop() {
        PrintWriter out = null;
        try {
            out = this.getResponse().getWriter();
            User loginUser = (User) getSession().getAttribute("loginUser");
            if (loginUser != null) {
                String comCode = loginUser.getComCode();
                Notice n = noticeServiceImpl.getLastTop(comCode);
                String json = BaseTool.toJson(n);
                out.print(json);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return null;
    }

    /**
     * 获取公告通知列表
     *
     * @return json
     */
    public String getNoticeList() {
        PrintWriter out = null;
        try {
            out = this.getResponse().getWriter();
            User loginUser = (User) getSession().getAttribute("loginUser");
            if (loginUser != null) {
                if (iDisplayLength == 0) {
                    iDisplayLength = -1;
                }
                int pageNum = (int) (Math.ceil(iDisplayStart / iDisplayLength)) + 1;
                /* 分页信息 */
                Page<Notice> pageInfo = new Page<>(iDisplayLength);
                pageInfo.setPageNo(pageNum);
                String comCode = loginUser.getComCode();
                if (StringUtils.isNotBlank(comCode)) {
                    notice.setComCode(comCode);
                }
                pageInfo = noticeServiceImpl.pageByNotice(pageInfo, notice);
                int iTotalRecords = pageInfo.getTotalCount();
                int iTotalDisplayRecords = pageInfo.getTotalCount() < 0 ? 0 : pageInfo.getTotalCount();
                /* 得到结果 */
                List<Notice> nList = pageInfo.getResult();
                /* 封装list */
                List<Map<String, Object>> noticeMapList = new ArrayList<>();
                if (nList != null && !nList.isEmpty() && nList.size() > 0) {
                    int i = (pageNum - 1) * iDisplayLength + 1;
                    for (Notice n : nList) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("no", i);// 序号
                        map.put("id", n.getId());
                        map.put("title", StringUtils.defaultString(n.getTitle(), ""));
                        map.put("content", StringUtils.defaultString(n.getContent(), ""));
                        map.put("top", n.getTop());
                        map.put("release", StringUtils.defaultString(n.getRelease(), ""));
                        map.put("releaseTime", StringUtils.defaultString(n.getReleaseTime(), ""));
                        map.put("isRelease", n.getIsRelease());
                        map.put("overdue", n.getOverdue());
                        map.put("overdueTime", StringUtils.defaultString(n.getOverdueTime(), ""));
                        noticeMapList.add(map);
                        i++;
                    }
                }
                Map<String, Object> jsonMap = new HashMap<>();
                jsonMap.put("iTotalRecords", iTotalRecords);
                jsonMap.put("iTotalDisplayRecords", iTotalDisplayRecords);
                jsonMap.put("aaData", noticeMapList);

                String json = BaseTool.toJson(jsonMap);
                out.print(json);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return null;
    }

    /**
     * 删除公告通知
     *
     * @return 成功标识
     */
    public String deleteNotice() {
        PrintWriter out = null;
        try {
            out = this.getResponse().getWriter();
            User loginUser = (User) getSession().getAttribute("loginUser");
            if (loginUser != null && StringUtils.isNotBlank(id)) {
                Notice n = noticeServiceImpl.getNoticeById(id);
                if (n != null) {
                    n.setIsDelete(1);
                    n.setUpdateUserId(loginUser.getId());
                    n.setUpdateUserName(loginUser.getUserName());
                    noticeServiceImpl.updateNotice(n);
                    out.print(0);
                    //添加系统日志
                    String userName = loginUser.getUserName();
                    String nowTime = TimeTool.getNowTime();
                    String content = "用户：" + userName + "，于" + nowTime + " 删除公告通知：" + n.getTitle() + "！";
                    PublicClass.addLog(userName, loginUser.getLoginName(), "公告通知", 2, content, logServiceImpl);
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return null;
    }

    /**
     * 跳转到修改或详情页面
     *
     * @return type
     */
    @SuppressWarnings("all")
    public String toUpdateOrDetail() {
        try {
            User loginUser = (User) getSession().getAttribute("loginUser");
            if (loginUser != null && StringUtils.isNotBlank(id)) {
                notice = noticeServiceImpl.getNoticeById(id);
                if (notice != null) {
                    if (type.equals("update")) {
                        return "update";
                    } else if (type.equals("detail")) {
                        return "detail";
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        }
        return null;
    }


    /**
     * 保存
     *
     * @return 成功标识
     */
    public String saveNotice() {
        PrintWriter out = null;
        try {
            out = this.getResponse().getWriter();
            User loginUser = (User) getSession().getAttribute("loginUser");
            if (loginUser != null && notice != null) {
                Date nowDate = new Date();
                if (StringUtils.isNotBlank(type) && type.equals("add")) {// 新增
                    notice.setId(BaseTool.getPK());
                    String userName = loginUser.getUserName();
                    notice.setRelease(userName);
                    String releaseTime = notice.getReleaseTime();//发布时间
                    if (StringUtils.isNotBlank(releaseTime)) {
                        Date releaseDate = TimeTool.stringToDate(releaseTime, "yyyy-MM-dd HH:mm:ss");
                        if (releaseDate.getTime() <= nowDate.getTime()) {
                            notice.setIsRelease(1);
                        }
                    }
                    String overdueTime = notice.getOverdueTime();
                    if (StringUtils.isNotBlank(overdueTime)) {
                        Date overdueDate = TimeTool.stringToDate(overdueTime, "yyyy-MM-dd HH:mm:ss");
                        if (overdueDate.getTime() <= nowDate.getTime()) {
                            notice.setOverdue(1);
                        }
                    }
                    if (StringUtils.isNotBlank(userName)) {
                        notice.setCreateUserId(loginUser.getId());
                        notice.setCreateUserName(userName);
                    }
                    String comCode = loginUser.getComCode();
                    if (StringUtils.isNotBlank(comCode)) {
                        notice.setComCode(comCode);
                    }
                    noticeServiceImpl.saveNotice(notice);
                    out.print("success");
                    //添加系统日志
                    String nowTime = TimeTool.getNowTime();
                    String content = "用户：" + userName + "，于" + nowTime + " 添加公告通知：" + notice.getTitle() + "！";
                    PublicClass.addLog(userName, loginUser.getLoginName(), "公告通知", 2, content, logServiceImpl);
                } else if (StringUtils.isNotBlank(type) && type.equals("update")) {// 修改
                    Notice oldNotice = noticeServiceImpl.getNoticeById(notice.getId());
                    if (oldNotice != null) {
                        oldNotice.setTitle(notice.getTitle());
                        oldNotice.setContent(notice.getContent());
                        String userName = loginUser.getUserName();
                        oldNotice.setRelease(userName);
                        String releaseTime = notice.getReleaseTime();//发布时间
                        oldNotice.setReleaseTime(releaseTime);
                        if (StringUtils.isNotBlank(releaseTime)) {
                            Date releaseDate = TimeTool.stringToDate(releaseTime, "yyyy-MM-dd HH:mm:ss");
                            if (releaseDate.getTime() <= nowDate.getTime()) {
                                oldNotice.setIsRelease(1);
                            }
                        }
                        String overdueTime = notice.getOverdueTime();
                        oldNotice.setOverdueTime(overdueTime);
                        if (StringUtils.isNotBlank(overdueTime)) {
                            Date overdueDate = TimeTool.stringToDate(overdueTime, "yyyy-MM-dd HH:mm:ss");
                            if (overdueDate.getTime() <= nowDate.getTime()) {
                                oldNotice.setOverdue(1);
                            }
                        }
                        if (StringUtils.isNotBlank(userName)) {
                            oldNotice.setUpdateUserId(loginUser.getId());
                            oldNotice.setUpdateUserName(userName);
                        }
                        noticeServiceImpl.updateNotice(oldNotice);
                        out.print("success");
                        //添加系统日志
                        String nowTime = TimeTool.getNowTime();
                        String content = "用户：" + userName + "，于" + nowTime + " 修改公告通知：" + notice.getTitle() + "！";
                        PublicClass.addLog(userName, loginUser.getLoginName(), "公告通知", 2, content, logServiceImpl);
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return null;
    }

    /**
     * 置顶或取消置顶公告通知
     *
     * @return 成功标识
     */
    public String topNotice() {
        PrintWriter out = null;
        try {
            out = this.getResponse().getWriter();
            User loginUser = (User) getSession().getAttribute("loginUser");
            if (loginUser != null && StringUtils.isNotBlank(id)) {
                Notice n = noticeServiceImpl.getNoticeById(id);
                if (n != null) {
                    Integer top = n.getTop();
                    if (top != null) {
                        String action;
                        if (top == 1) {
                            n.setTop(0);
                            action = "取消置顶";
                        } else {
                            n.setTop(1);
                            action = "置顶";
                        }
                        n.setTopTime(TimeTool.getNowTime());
                        String userName = loginUser.getUserName();
                        if (StringUtils.isNotBlank(userName)) {
                            n.setUpdateUserId(loginUser.getId());
                            n.setUpdateUserName(userName);
                        }
                        noticeServiceImpl.updateNotice(n);
                        out.print(0);
                        //添加系统日志
                        String nowTime = TimeTool.getNowTime();
                        String content = "用户：" + userName + "，于" + nowTime + " " + action + "公告通知：" + n.getTitle() + "！";
                        PublicClass.addLog(userName, loginUser.getLoginName(), "公告通知", 2, content, logServiceImpl);
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return null;
    }


    public int getIDisplayStart() {
        return iDisplayStart;
    }

    public void setIDisplayStart(int iDisplayStart) {
        this.iDisplayStart = iDisplayStart;
    }

    public int getIDisplayLength() {
        return iDisplayLength;
    }

    public void setIDisplayLength(int iDisplayLength) {
        this.iDisplayLength = iDisplayLength;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public Notice getNotice() {
        return notice;
    }

    public void setNotice(Notice notice) {
        this.notice = notice;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }
}
